package com.hifar.demo3;

import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class OperationDataParser {
    private Map<String, OperationValue> operationValues = new HashMap<>();
    
    public void parse(InputStream xmlStream) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(xmlStream);
        
        NodeList dataNodes = doc.getElementsByTagName("data");
        for (int i = 0; i < dataNodes.getLength(); i++) {
            Node dataNode = dataNodes.item(i);
            NamedNodeMap attributes = dataNode.getAttributes();
            String dataId = attributes.getNamedItem("dataID").getNodeValue();
            
            NodeList valueNodes = ((Element)dataNode).getElementsByTagName("values");
            for (int j = 0; j < valueNodes.getLength(); j++) {
                Node valueNode = valueNodes.item(j);
                String operator = valueNode.getAttributes().getNamedItem("operatorName").getNodeValue();
                String time = valueNode.getAttributes().getNamedItem("operatorTime").getNodeValue();
                
                Node value = ((Element)valueNode).getElementsByTagName("value").item(0);
                String valueText = value.getTextContent();
                String photo = value.getAttributes().getNamedItem("photo") != null ? 
                              value.getAttributes().getNamedItem("photo").getNodeValue() : null;
                
                OperationValue opValue = new OperationValue(dataId, valueText, operator, time, photo);
                
                // 只保留最后一次操作的值
                operationValues.put(dataId, opValue);
            }
        }
    }
    
    public OperationValue getOperationValue(String dataId) {
        return operationValues.get(dataId);
    }
    
    public static class OperationValue {
        private String dataId;
        private String value;
        private String operator;
        private String time;
        private String photo;
        
        public OperationValue(String dataId, String value, String operator, String time, String photo) {
            this.dataId = dataId;
            this.value = value;
            this.operator = operator;
            this.time = time;
            this.photo = photo;
        }
        
        // getters
        public String getDataId() { return dataId; }
        public String getValue() { return value; }
        public String getOperator() { return operator; }
        public String getTime() { return time; }
        public String getPhoto() { return photo; }
    }
}